package com.acane.instagram.feature.collection

import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.items
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import coil.compose.AsyncImage
import com.acane.instagram.R
import com.acane.instagram.core.config.Config
import com.acane.instagram.core.model.PostInfo
import com.acane.instagram.feature.common.SessionManager
import com.acane.instagram.feature.me.IconBadge
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@SuppressLint("StateFlowValueCalledInComposition", "CoroutineCreationDuringComposition")
@Composable
fun CollectionStaggeredGrid(
    coverList: List<PostInfo>,
    viewModel: CollectionViewModel,
    //toPost: (String, Int) -> Unit,
    toCollectionList: (Int) -> Unit
) {
    var thumbnailBitmap by remember { mutableStateOf<ImageBitmap?>(null) }
    val coroutineScope = rememberCoroutineScope()
    val context = LocalContext.current
    var postPosition by remember { mutableStateOf(0) }
    LazyVerticalStaggeredGrid(
        columns = StaggeredGridCells.Fixed(3),
        modifier = Modifier.fillMaxSize()
    ) {
        items(coverList) { cover ->
            LaunchedEffect(cover.id) {
                postPosition = viewModel.getPostPosition(cover.id, SessionManager.currentUser?.id!!)
            }
            val url = cover.thumbnailUrl
            Log.d("MeRoute", "🟢 目前封面缩略图 URL: $url")
            Log.d("MeRoute", "🟢 第一个URL: $url")
            val ulrType = viewModel.gridBoxInfo.value[cover]
            Box(modifier = Modifier.aspectRatio(1f)) {
                // 公共图片加载部分
                if (url.endsWith(".mp4")) {
                    val videoUrl = "${Config.ADDRESS}video/$url"
                    LaunchedEffect(videoUrl) {
                        coroutineScope.launch(Dispatchers.IO) {
                            thumbnailBitmap =
                                viewModel.generateVideoThumbnail(context, videoUrl).also {
                                    if (it == null) {
                                        Log.d("MeRoute", "🟢 缩略图生成失败: $videoUrl")
                                    }
                                }
                        }
                    }
                    // 显示缩略图
                    thumbnailBitmap?.let { bitmap ->
                        Log.d("MeRoute", "🟢 缩略图生成成功: $videoUrl")
                        Image(
                            bitmap = bitmap,
                            contentDescription = "视频缩略图",
                            modifier = Modifier
                                .fillMaxSize()
                                .clickable {
                                    toCollectionList(postPosition)
                                },
                            contentScale = ContentScale.Crop,
                        )
                    }?: run {
                        Log.d("MeRoute", "🟢 缩略图生成失败: $videoUrl")
                        // 显示默认占位图
                        Image(
                            painter = painterResource(id = R.drawable.ic_default_avatar),
                            contentDescription = "默认占位图",
                            modifier = Modifier
                                .fillMaxSize()
                                .clickable {
                                    toCollectionList( postPosition)
                                },
                            contentScale = ContentScale.Crop,
                        )
                    }
                } else {
                    AsyncImage(
                        model = "${Config.ADDRESS}avatars/$url",
                        contentDescription = "帖子封面",
                        contentScale = ContentScale.Crop,
                        modifier = Modifier
                            .fillMaxSize()
                            .clickable {
                                toCollectionList(postPosition)
                            },
                        error = painterResource(id = R.drawable.ic_default_avatar)
                    )
                }

                // 根据类型叠加图标
                when (ulrType) {
                    "isGrid" -> IconBadge(iconRes = R.drawable.square_multiple)
                    "isVideo" -> IconBadge(iconRes = R.drawable.video_unselected)
                }
            }
        }
    }
}